package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;

import android.app.Dialog;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.enums.PopupPosition;
import com.stark.picselect.config.PhotoConfig;
import com.stark.picselect.entity.SelectMediaEntity;
import com.stark.picselect.utils.MediaLoadManager;

import java.util.ArrayList;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.adapter.VideoAdapter;
import flc.ast.databinding.ActivityLocalVideoBinding;
import flc.ast.dialog.InfoDialog;
import flc.ast.dialog.PlayInfoDialog;
import flc.ast.dialog.VideoEditDialog;
import flc.ast.utils.Content;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.utils.FileUtil;
import stark.common.basic.utils.IntentUtil;
import stark.common.basic.utils.RxUtil;

public class LocalVideoActivity extends BaseAc<ActivityLocalVideoBinding> {

    private VideoAdapter videoAdapter;
    private List<SelectMediaEntity> listShow = new ArrayList<>();
    private BasePopupView editPopup;
    private int selPosition;
    private Dialog myDeleteDialog, myRenameDialog;
    private EditText dialogRename;


    @Override
    protected int onCreate() {
        return R.layout.activity_local_video;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(this, mDataBinding.event1Container);

        mDataBinding.ivLocalVideoBack.setOnClickListener(v -> onBackPressed());

        mDataBinding.rvVideoList.setLayoutManager(new GridLayoutManager(mContext, 2));
        videoAdapter = new VideoAdapter();
        mDataBinding.rvVideoList.setAdapter(videoAdapter);
        videoAdapter.addChildClickViewIds(R.id.ivVideoItemEdit);
        videoAdapter.setOnItemClickListener(this);
        videoAdapter.setOnItemChildClickListener(this);

        //删除弹框
        deleteDialog();
        //重命名弹框
        renameDialog();
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            //删除弹框
            case R.id.tvDialogDeleteConfirm://确定
                myDeleteDialog.dismiss();
                delete();
                break;
            case R.id.tvDialogDeleteCancel://取消
                myDeleteDialog.dismiss();
                break;
            //重命名弹框
            case R.id.tvDialogRenameConfirm://确定
                myRenameDialog.dismiss();
                String name = dialogRename.getText().toString();
                if (TextUtils.isEmpty(name)) {
                    ToastUtils.showShort(R.string.please_input_video_name);
                    return;
                }
                myRenameDialog.dismiss();
                FileUtils.rename(listShow.get(selPosition).getPath(), name + "." + FileUtils.getFileExtension(listShow.get(selPosition).getPath()));
                getData();
                break;
            case R.id.tvDialogRenameCancel://取消
                myRenameDialog.dismiss();
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        PlayLandscapeActivity.videoPath = videoAdapter.getItem(position).getPath();
        startActivity(PlayLandscapeActivity.class);
    }

    @Override
    public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
        switch (view.getId()) {
            case R.id.ivVideoItemEdit://编辑
                selPosition = position;
                editDialog(view);
                break;
        }
    }

    @Override
    protected void initData() {
        getData();
    }

    private void delete() {
        showDialog(getString(R.string.delete_ing));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                RxUtil.create(new RxUtil.Callback<String>() {

                    @Override
                    public void doBackground(ObservableEmitter<String> emitter) {
                        //从此文件夹删除
                        FileUtils.delete(listShow.get(selPosition).getPath());
                        emitter.onNext("");
                    }

                    @Override
                    public void accept(String path) {
                        getData();
                        dismissDialog();
                        ToastUtils.showShort(getString(R.string.delete_suc));
                    }
                });
            }
        }, 1000);
    }


    //获取视频和图片数据
    private void getData() {
        listShow.clear();
        RxUtil.create(new RxUtil.Callback<List<SelectMediaEntity>>() {
            @Override
            public void doBackground(ObservableEmitter<List<SelectMediaEntity>> emitter) {
                List<SelectMediaEntity> listSys = MediaLoadManager.loadAllMediaData(mContext, PhotoConfig.Mode.VIDEO);
                emitter.onNext(listSys);
            }

            @Override
            public void accept(List<SelectMediaEntity> selectMediaEntities) {
                if (selectMediaEntities.size() > 0) {
                    listShow.addAll(selectMediaEntities);
                    videoAdapter.setList(selectMediaEntities);
                    mDataBinding.rvVideoList.setVisibility(View.VISIBLE);
                    mDataBinding.tvVideoNoData.setVisibility(View.GONE);
                } else {
                    mDataBinding.rvVideoList.setVisibility(View.GONE);
                    mDataBinding.tvVideoNoData.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    private void editDialog(View view) {
        VideoEditDialog videoEditDialog = new VideoEditDialog(mContext);
        editPopup = new XPopup.Builder(mContext).popupPosition(PopupPosition.Bottom) //手动指定弹窗的位置
                .isDestroyOnDismiss(false) //对于只使用一次的弹窗，推荐设置这个
                .atView(view).hasShadowBg(false) // 去掉半透明背景
                .asCustom(videoEditDialog);
        videoEditDialog.setListener(new VideoEditDialog.Ilistener() {
            @Override
            public void clickDelete() {
                myDeleteDialog.show();
            }

            @Override
            public void clickShare() {
                IntentUtil.shareVideo(mContext, listShow.get(selPosition).getPath());
            }

            @Override
            public void clickRename() {
                dialogRename.setText(FileUtils.getFileNameNoExtension(listShow.get(selPosition).getPath()));
                myRenameDialog.show();
            }

            @Override
            public void clickAddFolder() {
                String filePath = FileUtil.generateFilePath(Content.myPrivacy, "." + FileUtils.getFileExtension(listShow.get(selPosition).getPath()));
                FileUtils.copy(listShow.get(selPosition).getPath(), filePath);
                ToastUtils.showShort(getString(R.string.add_suc));
            }

            @Override
            public void clickInfo() {
                showInfoDialog();
            }
        });
        editPopup.show();
    }

    //删除弹框
    private void deleteDialog() {
        myDeleteDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_delete, null);
        myDeleteDialog.setContentView(inflate);
        myDeleteDialog.setCancelable(true);
        Window dialogWindow = myDeleteDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.CENTER);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 1.0);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        TextView right = inflate.findViewById(R.id.tvDialogDeleteConfirm);
        TextView cancel = inflate.findViewById(R.id.tvDialogDeleteCancel);
        TextView tip = inflate.findViewById(R.id.tvDialogDeleteTip);
        tip.setText(getString(R.string.is_delete_video));
        right.setOnClickListener(this);
        cancel.setOnClickListener(this);
    }

    //重命名弹框
    private void renameDialog() {
        myRenameDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_rename, null);
        myRenameDialog.setContentView(inflate);
        myRenameDialog.setCancelable(true);
        Window dialogWindow = myRenameDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.CENTER);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 1.0);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        TextView right = inflate.findViewById(R.id.tvDialogRenameConfirm);
        TextView cancel = inflate.findViewById(R.id.tvDialogRenameCancel);
        TextView title = inflate.findViewById(R.id.tvDialogRenameTitle);
        title.setText(getString(R.string.edit_video_name));
        dialogRename = inflate.findViewById(R.id.etDialogRenameText);
        dialogRename.setHint(getString(R.string.input_video_name));
        right.setOnClickListener(this);
        cancel.setOnClickListener(this);
    }

    private void showInfoDialog() {
        InfoDialog dialog = new InfoDialog(mContext);
        dialog.videoPath = listShow.get(selPosition).getPath();
        dialog.show();
    }

}